const path = require('path');
const Sequelize = require('sequelize');
const mysqlConf = require('config-lite')(__dirname).mysql; //execSync
const noseq = new Sequelize('', mysqlConf.uname, mysqlConf.upass, mysqlConf.opts);
const seq = new Sequelize(mysqlConf.database, mysqlConf.uname, mysqlConf.upass, mysqlConf.opts);
const syncFun = () => {
	seq.sync().then(() => {
		console.log('init db ok');
	}).catch(err => {
		console.log('init db error', err);
	});
}

seq.authenticate().then(() => {
	syncFun();
}).catch(async (err) => {
	try {
		let createText = 'CREATE DATABASE IF NOT EXISTS';
		let chapterText = 'DEFAULT CHARSET utf8 COLLATE utf8_general_ci';
		await noseq.query(createText + ' nodebase ' + chapterText);
		setTimeout(syncFun, 100);
	} catch (e) {
		console.log('错误处理');
	}
});

/**
 * 定义数据模型的公共方法
 * @param {any} name 模型名称【数据库表名】
 * @param {any} attributes 数据字段集合
 * @returns 数据模型对象
 */
function defineModel(name, attributes) {
	let attrs = {}
	for (let key in attributes) {
		let value = attributes[key]
		if (typeof value === 'object' && value['type']) {
			value.allowNull = value.allowNull || false
			attrs[key] = value;
		} else {
			attrs[key] = { type: value, allowNull: false };
		}
	}
	// 调用seq的方法定义模型并返回
	return seq.define(name, attrs, {
		tableName: name,
		timestamps: false,
		hooks: {
			beforeValidate: function(obj) {
				let now = Date.now();
				if (obj.isNewRecord) {
					obj.createtime = now;
				}
				obj.updatetime = now;
			}
		}
	})
}
module.exports = defineModel